package com.zhitong.money.mapper;

import com.zhitong.money.entity.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;
import java.util.Map;


@Mapper
public interface RoleMapper {

    @Results(id = "roleMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "description",property = "description"),
            @Result(column = "status",property = "status"),
            @Result(column = "id",property = "permissions",
                    many = @Many(select = "com.zhitong.money.mapper.PermissionMapper.findPermissionByRid",fetchType = FetchType.EAGER)),
            @Result(column = "id",property = "menus",
                    many = @Many(select = "com.zhitong.money.mapper.MenuMapper.findMenuByRid",fetchType = FetchType.EAGER))
    })
    @Select("select * from role where id=#{id}")
    public Role findRoleById(String id);

    @ResultMap("roleMap")
    @Select("select * from role where id in (select rid from user_role where uid = #{uid})")
    public List<Role> findRoleByUid(String uid);

    @ResultMap("roleMap")
    @Select("select * from role where name=#{name}")
    public Role findRoleByName(String name);

    @ResultMap("roleMap")
    @Select("select * from role")
    public List<Role> findAllRole();

    @ResultMap("roleMap")
    @Select({
            "<script>",
            "select * from role",
            "<where>",
            "<if test='name != null and name!=\"\"'>and name like concat(concat('%',#{name},'%'))</if>",
            "<if test='status != null and status!=\"\"'>and status = #{status}</if>",
            "</where>",
            "</script>"
    })
    public List<Role> findRoleByMap(Map<String,Object> map);

    @Insert("insert into role values(#{id},#{name},#{description},#{status})")
    public void addRole(Role role);

    @Update({
            "<script>",
            "update role",
            "<trim prefix='set' suffixOverrides=','>",
            "<if test='name!=null and name != \"\"'> name=#{name},</if>",
            "<if test='description!=null and description!=\"\"'> description=#{description},</if>",
            "<if test='status!=null and status != \"\"'> status=#{status},</if>",
            "</trim>",
            "where id = #{id}",
            "</script>"
    })
    public void updateRole(Map<String,Object> map);

    @Delete("delete from role where id=#{id}")
    public int delRole(String id );

    @Delete({
            "<script>",
            "delete from role",
            "where id in",
            "<foreach item='item' collection='ids' separator=',' open='(' close=')' index=''>",
            "#{item}",
            "</foreach>",
            "</script>"
    })
    public int delRolesByIds(List<String> ids);


}
